// 医护人员个人资料页面
const app = getApp();
const staffService = require('../../../services/staff');

Page({
  data: {
    staffInfo: null,
    loading: true,
    departments: [],
    genderOptions: [
      { id: 1, name: '男' },
      { id: 2, name: '女' }
    ],
    titleOptions: [
      { id: 1, name: '主任医师' },
      { id: 2, name: '副主任医师' },
      { id: 3, name: '主治医师' },
      { id: 4, name: '住院医师' },
      { id: 5, name: '护士长' },
      { id: 6, name: '护士' }
    ],
    uploadingAvatar: false
  },

  onLoad: function() {
    this.loadStaffInfo();
    this.loadDepartments();
  },

  // 加载医护人员信息
  loadStaffInfo: function() {
    this.setData({ loading: true });
    
    // 先尝试从本地获取
    const staffInfo = app.getStaffInfo();
    if (staffInfo) {
      this.setData({ 
        staffInfo: staffInfo,
        loading: false
      });
    }
    
    // 无论是否从本地获取到，都从服务器拉取最新数据
    staffService.getStaffInfo()
      .then(res => {
        this.setData({
          staffInfo: res,
          loading: false
        });
        
        // 更新全局数据
        app.globalData.staffInfo = res;
        wx.setStorageSync('staffInfo', res);
      })
      .catch(err => {
        console.error('获取医护人员信息失败', err);
        if (!this.data.staffInfo) {
          wx.showToast({
            title: '获取信息失败，请重试',
            icon: 'none'
          });
        }
        this.setData({ loading: false });
      });
  },
  
  // 加载科室列表
  loadDepartments: function() {
    staffService.getDepartments()
      .then(res => {
        console.log('获取到科室列表:', res);
        // 处理返回的数据，确保将其转换为数组
        const departments = Array.isArray(res) ? res : (res.records || []);
        this.setData({
          departments: departments
        });
        
        // 如果staffInfo中有departmentId但没有department名称，根据id查找对应科室名称
        if (this.data.staffInfo && this.data.staffInfo.departmentId && !this.data.staffInfo.department) {
          const department = departments.find(item => item.id === this.data.staffInfo.departmentId);
          if (department) {
            this.setData({
              'staffInfo.department': department.name
            });
            // 更新全局数据
            const app = getApp();
            const staffInfo = app.getStaffInfo();
            if (staffInfo) {
              staffInfo.department = department.name;
              app.globalData.staffInfo = staffInfo;
              wx.setStorageSync('staffInfo', staffInfo);
            }
          }
        }
      })
      .catch(err => {
        console.error('获取科室列表失败', err);
      });
  },
  
  // 表单输入
  onInput: function(e) {
    const field = e.currentTarget.dataset.field;
    const value = e.detail.value;
    
    // 使用对象展开语法更新staffInfo中的指定字段
    this.setData({
      ['staffInfo.' + field]: value
    });
  },

  // 选择性别
  bindGenderChange: function(e) {
    this.setData({
      'staffInfo.gender': parseInt(e.detail.value) + 1 // 索引从0开始，但性别值从1开始
    });
  },
  
  // 选择职称
  bindTitleChange: function(e) {
    const selectedIndex = e.detail.value;
    const selectedTitle = this.data.titleOptions[selectedIndex].name;
    
    this.setData({
      'staffInfo.title': selectedTitle
    });
  },
  
  // 选择科室
  bindDepartmentChange: function(e) {
    const selectedIndex = e.detail.value;
    const selectedDepartment = this.data.departments[selectedIndex];
    
    this.setData({
      'staffInfo.departmentId': selectedDepartment.id,
      'staffInfo.department': selectedDepartment.name
    });
  },
  
  // 上传头像
  uploadAvatar: function() {
    const that = this;
    
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function(res) {
        const tempFilePath = res.tempFilePaths[0];
        
        // 显示上传中
        that.setData({ uploadingAvatar: true });
        
        // 显示加载
        wx.showLoading({
          title: '上传中...',
          mask: true
        });
        
        // 上传到服务器
        wx.uploadFile({
          url: app.globalData.baseUrl + '/staff/avatar',
          filePath: tempFilePath,
          name: 'file',
          header: {
            'Content-Type': 'multipart/form-data',
            'Authorization': wx.getStorageSync('token')
          },
          success: function(uploadRes) {
            let result;
            try {
              result = JSON.parse(uploadRes.data);
            } catch(e) {
              console.error('解析上传结果失败', e);
              wx.hideLoading();
              that.setData({ uploadingAvatar: false });
              wx.showToast({
                title: '上传失败，请重试',
                icon: 'none'
              });
              return;
            }
            
            if (result.code === 200) {
              // 更新头像URL
              that.setData({
                'staffInfo.avatar': result.data.url
              });
              
              // 更新全局数据
              const staffInfo = app.getStaffInfo();
              if (staffInfo) {
                staffInfo.avatar = result.data.url;
                app.globalData.staffInfo = staffInfo;
                wx.setStorageSync('staffInfo', staffInfo);
              }
              
              wx.showToast({
                title: '上传成功',
                icon: 'success'
              });
            } else {
              wx.showToast({
                title: result.message || '上传失败',
                icon: 'none'
              });
            }
          },
          fail: function(err) {
            console.error('上传头像失败', err);
            wx.showToast({
              title: '网络错误，请重试',
              icon: 'none'
            });
          },
          complete: function() {
            wx.hideLoading();
            that.setData({ uploadingAvatar: false });
          }
        });
      }
    });
  },
  
  // 保存信息
  saveProfile: function() {
    // 显示加载
    wx.showLoading({
      title: '保存中...',
      mask: true
    });
    
    // 构建请求数据
    const data = {
      name: this.data.staffInfo.name,
      gender: this.data.staffInfo.gender,
      title: this.data.staffInfo.title,
      departmentId: this.data.staffInfo.departmentId,
      introduction: this.data.staffInfo.introduction
    };
    
    // 发送更新请求
    staffService.updateStaffInfo(data)
      .then(res => {
        wx.hideLoading();
        wx.showToast({
          title: '保存成功',
          icon: 'success'
        });
        
        // 更新全局数据
        app.globalData.staffInfo = this.data.staffInfo;
        wx.setStorageSync('staffInfo', this.data.staffInfo);
        
        // 返回上一页
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      })
      .catch(err => {
        console.error('更新医护人员信息失败', err);
        wx.hideLoading();
        wx.showToast({
          title: err.message || '保存失败，请重试',
          icon: 'none'
        });
      });
  }
}); 